<?php
/**
 * 门店订单控制器
 * Created by PhpStorm.
 * Author: 芸众商城 www.yunzshop.com
 * Date: 2024/1/1
 * Time: 上午10:00
 */

namespace App\Http\Controllers\Api\store;

use App\Common\Components\ApiController;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Http\Controllers\Api\BaseApiController;

class StoreOrderController extends BaseApiController
{
    protected $publicController = ['StoreOrder'];
    protected $publicAction = ['index', 'detail', 'cashierOrderList', 'cashierOrderDetail', 'closeOrder'];
    protected $ignoreAction = ['index', 'detail', 'cashierOrderList', 'cashierOrderDetail', 'closeOrder'];

    /**
     * 收银台订单列表接口
     */
    public function cashierOrderList(Request $request)
    {
        $param = $request->input('param', []);
        $organid = $request->input('organid');
        
        // 获取请求参数
        $page = $param['page'] ?? 1;
        $limit = $param['limit'] ?? 10;
        $orderNo = $param['orderNo'] ?? ''; // 订单编号
        $memberId = $param['memberId'] ?? ''; // 会员ID
        $memberNickname = $param['memberNickname'] ?? ''; // 会员昵称
        $memberMobile = $param['memberMobile'] ?? ''; // 会员手机号
        $status = $param['status'] ?? ''; // 订单状态
        $storeId = $organid; // 门店ID
        $startTime = $param['startTime'] ?? ''; // 开始时间
        $endTime = $param['endTime'] ?? ''; // 结束时间
        $paymentMethod = $param['paymentMethod'] ?? ''; // 支付方式
        
        // 收银台插件ID (参考yhym项目: Store::CASHIER_PLUGIN_ID = 31)
        $cashierPluginId = 31;
        
        // 根据门店ID获取收银员ID (cashier_id)
        $cashierId = null;
        if ($storeId) {
            $store = DB::table('ims_yz_store')
                ->where('id', $storeId)
                ->first();
            if ($store) {
                $cashierId = $store->cashier_id;
            }
        }
        
        // 构建查询条件 - 参考yhym的ShopOrder::getCashierOrderList逻辑
        $query = DB::table('ims_yz_order as o')
            ->leftJoin('ims_yz_plugin_cashier_order as co', 'co.order_id', '=', 'o.id')
            ->leftJoin('ims_mc_members as m', 'o.uid', '=', 'm.uid')
            ->leftJoin('ims_yz_order_pay_order as opo', 'o.id', '=', 'opo.order_id')
            ->leftJoin('ims_yz_order_pay as op', 'opo.order_pay_id', '=', 'op.id')
            ->leftJoin('ims_yz_pay_type as pt', 'o.pay_type_id', '=', 'pt.id')
            ->select([
                'o.id',
                'o.order_sn',
                'o.price',
                'o.goods_price',
                'o.status',
                'o.create_time',
                'o.pay_time',
                'o.finish_time',
                'o.cancel_time',
                'o.note as remark',
                'o.uid as member_uid',
                'o.pay_type_id as pay_type',
                'pt.name as pay_type_name',
                'm.uid as member_id',
                'm.nickname as member_nickname',
                'm.avatar as member_avatar',
                'm.mobile as member_mobile',
                'm.realname as member_realname',
                'op.pay_sn',
                'co.amount as cashier_amount',
                'co.fee_percentage',
                'co.cashier_id',
                'o.shop_name',
                DB::raw('(SELECT GROUP_CONCAT(title SEPARATOR ", ") FROM ims_yz_order_goods WHERE order_id = o.id LIMIT 3) as goods_titles'),
                DB::raw('(SELECT thumb FROM ims_yz_order_goods WHERE order_id = o.id ORDER BY id ASC LIMIT 1) as goods_thumb')
            ])
            ->where('o.plugin_id', $cashierPluginId); // 只查询收银台订单
            // ->where('o.status', '>=', 1); // 只查询待发货及以上状态的订单
        
        // 如果有收银员ID，按收银员ID过滤
        if ($cashierId) {
            $query->where('co.cashier_id', $cashierId);
        }
        
        // 添加筛选条件
        if (!empty($orderNo)) {
            $query->where('o.order_sn', 'like', '%' . $orderNo . '%');
        }
        
        if (!empty($memberId)) {
            $query->where('o.uid', $memberId);
        }
        
        if (!empty($memberNickname)) {
            $query->where('m.nickname', 'like', '%' . $memberNickname . '%');
        }
        
        if (!empty($memberMobile)) {
            $query->where('m.mobile', 'like', '%' . $memberMobile . '%');
        }
        
        if (!empty($status)&&$status != -2) {
            if($status == -10){
                $query->where('o.status', 0);
            }else{
                $query->where('o.status', $status);
            }
        }
        
        if (!empty($startTime)) {
            $startTimestamp = strtotime($startTime);
            $query->where('co.created_at', '>=', $startTimestamp);
        }
        
        if (!empty($endTime)) {
            $endTimestamp = strtotime($endTime);
            $query->where('co.created_at', '<', $endTimestamp+86400);
        }
        
        if (!empty($paymentMethod)) {
            $query->where('o.pay_type_id', $paymentMethod);
        }
        
        // 计算总金额
        $totalPrice = (clone $query)->sum('o.price');
        
        // 获取总数
        $total = $query->count();
        
        // 分页查询
        $orders = $query->orderBy('o.id', 'desc')
            ->offset(($page - 1) * $limit)
            ->limit($limit)
            ->get();
        
        // 处理订单状态显示
        $statusMap = [
            0 => '待支付',
            1 => '待发货',
            2 => '待收货',
            3 => '已完成',
            -1 => '已关闭',
            -2 => '退款中',
            -3 => '已退款'
        ];
        
        // 处理数据
        foreach ($orders as $order) {
            $order->status_text = $statusMap[$order->status] ?? '未知状态';
            // pay_type_name 已经从数据库中获取，如果为空则设置默认值
            $order->pay_type_name = $order->pay_type_name ?: '未知支付方式';
            $order->create_time = date('Y-m-d H:i:s', $order->create_time);
            $order->pay_time = $order->pay_time ? date('Y-m-d H:i:s', $order->pay_time) : '';
            $order->finish_time = $order->finish_time ? date('Y-m-d H:i:s', $order->finish_time) : '';
            $order->cancel_time = $order->cancel_time ? date('Y-m-d H:i:s', $order->cancel_time) : '';
            
            // 格式化金额
            $order->price = number_format($order->price, 2, '.', '');
            $order->goods_price = number_format($order->goods_price, 2, '.', '');
            $order->cashier_amount = $order->cashier_amount ? number_format($order->cashier_amount, 2, '.', '') : '0.00';
            $order->fee_percentage = $order->fee_percentage ? number_format($order->fee_percentage, 2, '.', '') : '0.00';
        }
        
        $data = [
            'list' => $orders,
            'total' => $total,
            'total_price' => number_format($totalPrice, 2, '.', ''),
            'page' => $page,
            'limit' => $limit,
            'pages' => ceil($total / $limit)
        ];
        
        return $this->successJson('获取订单列表成功', $data);
    }
    
    /**
     * 收银台订单详情接口
     */
    public function cashierOrderDetail(Request $request)
    {
        $orderId = $request->input('param.orderId');
        
        if (empty($orderId)) {
            return $this->errorJson('订单ID不能为空');
        }
        
        // 查询订单基本信息 - 包含收银台订单信息
        $order = DB::table('ims_yz_order as o')
            ->leftJoin('ims_mc_members as m', 'o.uid', '=', 'm.uid')
            ->leftJoin('ims_yz_order_address as oa', 'o.id', '=', 'oa.order_id')
            ->leftJoin('ims_yz_plugin_cashier_order as co', 'o.id', '=', 'co.order_id')
            ->leftJoin('ims_yz_store as s', 'co.cashier_id', '=', 's.cashier_id')
            ->leftJoin('ims_yz_address as province', 's.province_id', '=', 'province.id')
            ->leftJoin('ims_yz_address as city', 's.city_id', '=', 'city.id')
            ->leftJoin('ims_yz_address as district', 's.district_id', '=', 'district.id')
            ->leftJoin('ims_yz_order_pay_order as opo', 'o.id', '=', 'opo.order_id')
            ->leftJoin('ims_yz_order_pay as op', 'opo.order_pay_id', '=', 'op.id')
            ->leftJoin('ims_yz_pay_type as pt', 'o.pay_type_id', '=', 'pt.id')
            ->where('o.id', $orderId)
            ->select([
                'o.*',
                'm.uid as member_id',
                'm.nickname as member_nickname',
                'm.avatar as member_avatar',
                'm.mobile as member_mobile',
                'm.realname as member_realname',
                'oa.realname as receiver_name',
                'oa.mobile as receiver_mobile',
                'oa.address as receiver_address',
                'op.pay_sn',
                'pt.name as pay_type_name',
                'co.amount as cashier_amount',
                'co.fee_percentage',
                'co.cashier_id',
                'co.has_withdraw',
                'co.has_settlement',
                's.id as store_id',
                's.store_name',
                's.thumb as store_thumb',
                's.banner_thumb as store_banner',
                's.mobile as store_mobile',
                's.address as store_address_detail',
                'province.areaname as province_name',
                'city.areaname as city_name',
                'district.areaname as district_name',
                's.longitude as store_longitude',
                's.latitude as store_latitude',
                's.business_hours_start',
                's.business_hours_end',
                's.store_introduce'
            ])
            ->first();
        
        if (!$order) {
            return $this->errorJson('订单不存在');
        }
        
        // 查询订单商品信息
        $orderGoods = DB::table('ims_yz_order_goods')
            ->where('order_id', $orderId)
            ->select([
                'id',
                'goods_id',
                'title',
                'goods_option_title',
                'goods_sn',
                'total',
                'price',
                'thumb as goods_thumb'
            ])
            ->get();
        
        // 处理订单状态显示
        $statusMap = [
            0 => '待支付',
            1 => '待发货',
            2 => '待收货',
            3 => '已完成',
            -1 => '已关闭',
            -2 => '退款中',
            -3 => '已退款'
        ];
        
        // 处理订单数据
        $order->status_text = $statusMap[$order->status] ?? '未知状态';
        // pay_type_name 已经从数据库中获取，如果为空则设置默认值
        $order->pay_type_name = $order->pay_type_name ?: '未知支付方式';
        $order->create_time = date('Y-m-d H:i:s', $order->create_time);
        $order->pay_time = $order->pay_time ? date('Y-m-d H:i:s', $order->pay_time) : '';
        $order->finish_time = $order->finish_time ? date('Y-m-d H:i:s', $order->finish_time) : '';
        $order->cancel_time = $order->cancel_time ? date('Y-m-d H:i:s', $order->cancel_time) : '';
        
        // 格式化金额
        $order->price = number_format($order->price, 2, '.', '');
        $order->goods_price = number_format($order->goods_price, 2, '.', '');
        $order->dispatch_price = number_format($order->dispatch_price ?? 0, 2, '.', '');
        $order->cashier_amount = $order->cashier_amount ? number_format($order->cashier_amount, 2, '.', '') : '0.00';
        $order->fee_percentage = $order->fee_percentage ? number_format($order->fee_percentage, 2, '.', '') : '0.00';
        
        // 处理提现和结算状态
        $order->has_withdraw_text = $order->has_withdraw == 1 ? '已提现' : '未提现';
        $order->has_settlement_text = $order->has_settlement == 1 ? '已结算' : '未结算';
        
        // 拼接完整的店铺地址
        $addressParts = array_filter([
            $order->province_name ?? '',
            $order->city_name ?? '',
            $order->district_name ?? '',
            $order->store_address_detail ?? ''
        ]);
        $order->store_address = implode('', $addressParts);
        
        // 处理商品数据
        foreach ($orderGoods as $goods) {
            $goods->goods_title = $goods->title;
            $goods->price = number_format($goods->price, 2, '.', '');
            $goods->total_price = number_format($goods->price * $goods->total, 2, '.', '');
        }
        
        
        $data = [
            'order' => $order,
            'orderGoods' => $orderGoods
        ];
        
        return $this->successJson('获取订单详情成功', $data);
    }
    
    /**
     * 订单列表接口（别名，兼容旧接口）
     */
    public function index(Request $request)
    {
        return $this->cashierOrderList($request);
    }
    
    /**
     * 订单详情接口（别名，兼容旧接口）
     */
    public function detail(Request $request)
    {
        return $this->cashierOrderDetail($request);
    }
    
    /**
     * 获取订单状态列表
     */
    public function getOrderStatus()
    {
        $statusList = [
            ['value' => '', 'label' => '全部订单'],
            ['value' => 0, 'label' => '待支付'],
            ['value' => 1, 'label' => '待发货'],
            ['value' => 2, 'label' => '待收货'],
            ['value' => 3, 'label' => '已完成'],
            ['value' => -1, 'label' => '已关闭'],
            ['value' => -2, 'label' => '退款中'],
            ['value' => -3, 'label' => '已退款']
        ];
        
        return $this->successJson('获取订单状态列表成功', $statusList);
    }
    
    /**
     * 获取支付方式列表
     */
    public function getPaymentMethods()
    {
        $paymentMethods = [
            ['value' => '', 'label' => '全部支付方式'],
            ['value' => 'wechat', 'label' => '微信支付'],
            ['value' => 'alipay', 'label' => '支付宝'],
            ['value' => 'balance', 'label' => '余额支付'],
            ['value' => 'cash', 'label' => '现金支付']
        ];
        
        return $this->successJson('获取支付方式列表成功', $paymentMethods);
    }
    
    /**
     * 关闭订单（仅限待支付状态）
     */
    public function closeOrder(Request $request)
    {
        $orderId = $request->input('param.orderId');
        $reason = $request->input('param.reason', ''); // 关闭原因
        
        if (empty($orderId)) {
            return $this->errorJson('订单ID不能为空');
        }
        
        // 查询订单
        $order = DB::table('ims_yz_order')
            ->where('id', $orderId)
            ->first();
        
        if (!$order) {
            return $this->errorJson('订单不存在');
        }
        
        // 只有待支付状态(status = 0)的订单可以关闭
        if ($order->status != 0) {
            return $this->errorJson('只有待支付订单才能关闭');
        }
        
        // 更新订单状态为已关闭(-1)
        $updateData = [
            'status' => -1,
            'cancel_time' => time(),
            'updated_at' => time()
        ];
        
        // 如果有关闭原因，记录到备注中
        if (!empty($reason)) {
            $updateData['close_reason'] = $reason;
        }
        
        $result = DB::table('ims_yz_order')
            ->where('id', $orderId)
            ->update($updateData);
        
        if ($result) {
            return $this->successJson('订单已关闭');
        } else {
            return $this->errorJson('关闭订单失败');
        }
    }
}
